import pygame
import math
from constants import *

class Bullet:
    def __init__(self, x, y, angle, is_player_bullet=True):
        self.x = x
        self.y = y
        self.angle = angle
        self.is_player_bullet = is_player_bullet
        self.distance_traveled = 0

        # 计算速度分量
        angle_rad = math.radians(angle)
        self.dx = math.cos(angle_rad) * BULLET_SPEED / 60  # 60 FPS
        self.dy = -math.sin(angle_rad) * BULLET_SPEED / 60

    def update(self):
        """更新炮弹位置"""
        self.x += self.dx
        self.y += self.dy

        # 计算移动距离
        distance_this_frame = math.sqrt(self.dx**2 + self.dy**2)
        self.distance_traveled += distance_this_frame

        # 检查是否超出最大射程或屏幕边界
        return self.is_active()

    def draw(self, screen):
        """绘制炮弹"""
        pygame.draw.circle(screen, BULLET_COLOR,
                         (int(self.x), int(self.y)),
                         BULLET_RADIUS)

    def is_active(self):
        """检查炮弹是否仍然有效"""
        # 检查最大射程
        if self.distance_traveled >= BULLET_MAX_RANGE:
            return False

        # 检查是否在屏幕内
        if (self.x < 0 or self.x > WINDOW_WIDTH or
            self.y < 0 or self.y > WINDOW_HEIGHT):
            return False

        return True

    def check_collision(self, tank):
        """检查是否击中坦克"""
        # 计算炮弹到坦克中心的距离
        dx = self.x - tank.x
        dy = self.y - tank.y
        distance = math.sqrt(dx**2 + dy**2)

        # 简单的圆形碰撞检测
        if distance <= TANK_WIDTH/2:
            # 计算伤害值（1-15之间）
            # 根据击中位置计算伤害，中心点最大伤害
            damage = int(15 * (1 - distance/(TANK_WIDTH/2)))
            damage = max(1, min(15, damage))
            return damage
        return 0